package cn.dubito.springboot.learning.controller;


import cn.dubito.springboot.learning.dataobject.ProductCategory;
import cn.dubito.springboot.learning.dataobject.ProductInfo;
import cn.dubito.springboot.learning.service.CategoryService;
import cn.dubito.springboot.learning.service.ProductService;
import cn.dubito.springboot.learning.utils.ResultUtil;
import cn.dubito.springboot.learning.vo.ProductInfoVO;
import cn.dubito.springboot.learning.vo.ProductVO;
import cn.dubito.springboot.learning.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liliang
 * @description:
 * @date 2018/1/10.
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVO list() {
        // 所有上架商品
        List<ProductInfo> productInfoList = productService.findUpAll();
        // 查询类目
        List<Integer> categoryTypeList = new ArrayList<>();
        categoryTypeList = productInfoList
                .stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

        //数据拼接
        List<ProductVO> productVOList = new ArrayList<>();
        for(ProductCategory productCategory : categoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());

            List<ProductInfoVO> productInfoVOList =  new ArrayList<>();
            for (ProductInfo productInfo: productInfoList) {
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultUtil.success(productVOList);
    }
}
